import axios from "axios";
import {ElMessage, switchProps} from 'element-plus';
import { GET_TOKEN } from '@/utils/token';
let request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    
    timeout: 500000000000
})

//请求拦截器
request.interceptors.request.use(config =>{
    let token = GET_TOKEN();
    config.headers = config.headers || {}; // 确保headers对象存在
    config.headers.TOKEN = token;
   
    return config;
})

//响应拦截器
request.interceptors.response.use((response)=>{
    const res =  response.data;
    if(res.code !==200){
        ElMessage({
            type:'error',
            message: res.msg
        })
        return Promise.reject(new Error(res.msg))
    }
    return response.data;
},
(error)=>{
    let msg = '';
    let status = error.response.status;
    switch(status){
        case 401:
            msg = 'token过期,请重新登录';
            break;
        case 403:
            msg = '无权访问';
            break;
        case 404:
            msg = "无法链接请求地址"
            break;
        case 500:
            msg = "服务器出现错误";
            break;
        default:
            msg = '无网络';
    }
    ElMessage({
        type:'error',
        message: msg
    })
    return Promise.reject(error);

})

export default request;